package com.dch.realm;

import cn.hutool.core.util.StrUtil;
import com.dch.constant.ShiroConstant;

import com.dch.enums.UserTypeEnum;

import com.dch.system.entity.SysResources;
import com.dch.system.entity.SysRole;
import com.dch.system.entity.SysUser;
import com.dch.system.service.SysResourcesService;
import com.dch.system.service.SysRoleService;
import com.dch.system.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class AccountRealm extends AuthorizingRealm {
    /*用户表*/
    @Resource
    private SysUserService userService;
    /*用户权限表*/
    @Resource
    private SysResourcesService resourcesService;

    /*用户角色表*/
    @Resource
    private SysRoleService roleService;

    /**
     * 授权判断放在这个方法里
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录信息
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser) subject.getPrincipal();

        //设置角色
        Set<String> roles = new HashSet<>();
        List<SysRole> roleList = this.roleService.listRolesByUserId(sysUser.getId());
        for (SysRole role: roleList) {
            roles.add(role.getName());
        }

        //roles.add(sysUser.getRole());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        //设置权限
        //info.addStringPermission(account.getPerms());
        // ROOT用户默认拥有所有权限
        List<SysResources> resourcesList = null;

        if (UserTypeEnum.ROOT.toString().equalsIgnoreCase(sysUser.getUserType())) {
            resourcesList = resourcesService.list();
        } else {
            resourcesList = resourcesService.listByUserId(sysUser.getId());
        }
        if (!CollectionUtils.isEmpty(resourcesList)) {
            Set<String> permissionSet = new HashSet<>();
            for (SysResources resources : resourcesList) {
                String permission = null;
                if (!StrUtil.isEmpty(permission = resources.getPermission())) {
                    permissionSet.addAll(Arrays.asList(permission.trim().split(",")));
                }
            }
            info.setStringPermissions(permissionSet);
        }
        return null;
    }

    /**
     * 认证，登录赋予权限
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        SysUser sysUser = this.userService.findByUsername(token.getUsername());
        if(sysUser == null){
            //密码加密
            String md5 = new Md5Hash(sysUser.getPassword(), ShiroConstant.VALUE.getMd5Key()).toString();
            // 验证密码
            return  new SimpleAuthenticationInfo(sysUser, md5, getName());
        }
        return null;

    }
}
